package com.zhaotianhao.check.userserver.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhaotianhao.check.userserver.common.JsonResult;
import com.zhaotianhao.check.userserver.entity.User;
import com.zhaotianhao.check.userserver.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Z-7
 * @since 2022-03-29
 */
@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Value("${jwt.key}")
    private String jwtKey;
    @Autowired
    private IUserService iUserService;

    @PostMapping("login")
    public JsonResult loginPost(@RequestBody User user) {
        // 判断用户名和密码不为空
        if (StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPwd())) {
            return JsonResult.faild("用户名或密码不能为空");
        }

        // 查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>().eq("username", user.getUsername());
        User login = iUserService.getOne(queryWrapper);

        if (login == null) {
            return JsonResult.faild("用户名或密码错误");
        }
        if (!user.getPwd().equals(login.getPwd())) {
            return JsonResult.faild("用户名或密码错误");
        }

        log.info("用户：{}", user.getUsername()+"登录成功");
        // 登录成功 生成token传到前台
        String token = JWT.create()
                .setPayload("username", login.getUsername()) // 用户数据
                .setPayload("role",login.getRole())
                .setExpiresAt(DateUtil.offsetMinute(new Date(), 10)) // 过期时间
                .setKey(jwtKey.getBytes()) // 加密
                .sign(); // 签名

        return JsonResult.successd(token);
    }

    @PostMapping("register")
    public boolean register(@RequestBody User user) {
        // 默认为普通用过
        return iUserService.save(user.setRole("user"));
    }

    public static void main(String[] args) throws InterruptedException {
        String token = JWT.create()
                .setPayload("username", "zhangsan")
                .setExpiresAt(DateUtil.offsetSecond(new Date(), 1))
                .setKey("1234".getBytes())
                .sign();
        System.out.println(token);
        Thread.sleep(2000);
        boolean validate = JWT.of(token).setKey("1234".getBytes()).validate(0);
        System.out.println(validate);
    }
}
